import { matchRoutesGroups } from '@/permissonsRoutes';
import { getPermissions, login } from '@/services/ant-design-pro/login';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Helmet, history, useIntl, useModel } from '@umijs/max';
import { Button, Form, Input, message } from 'antd';
import React, { useEffect } from 'react';
import Settings from '../../../../config/defaultSettings';
import styles from './index.less';

const Login: React.FC = () => {
  const { setInitialState } = useModel('@@initialState');

  useEffect(() => {
    /**
     * 本地没有token 重置initialState
     * 1.从request的响应拦截器 跳转到登录页
     * 2.app.jsx里的layout onPageChange  里的跳转到登录页
     * 3.点击退出登录 跳转到登录页
     * 以上三种情况都需要触发initialState的重置
     */
    //如果本地没有token,则重置initialState 因为有可能是从request的响应拦截器跳转到登录页的 响应拦截器无法重置initialState
    if (!localStorage.getItem('token')) {
      setInitialState((s) => ({
        ...s,
        isLogin: false,
        currentUser: undefined,
        permissons: [],
      }));
    }
  }, []);

  const intl = useIntl();

  //登录
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const { username, password } = values;
      const { code, msg, data } = await login({ username, password });

      if (code === 0) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        //存储token到本地
        localStorage.setItem('token', data?.token);

        //获取权限
        let permissons: any[] = [];
        let functions_groups = [];
        const res = await getPermissions();
        if (res.code === 0) {
          functions_groups = res.data?.functions_groups;
          permissons = matchRoutesGroups(functions_groups);
        }
        const currentUser = {
          ...data,
          functions_groups,
        };
        //存储当前用户到本地
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        // flushSync(() => {
        setInitialState((s: any) => {
          return {
            ...s,
            isLogin: true,
            permissons: permissons,
            currentUser: currentUser,
          };
        });
        // });

        //跳转到首页 或者跳转到登录前的页面
        setTimeout(() => {
          const urlParams = new URL(window.location.href).searchParams;
          history.replace(urlParams.get('redirect') || '/');
        }, 300);
        return;
      } else {
        const defaultLoginFailureMessage = intl.formatMessage({
          id: 'errors',
          defaultMessage: msg,
        });
        message.error(defaultLoginFailureMessage);
      }
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  // const { code, msg } = userLoginState;

  return (
    <div className={styles.containerClassName}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <div className={styles.loginFrom}>
        <div
          style={{
            fontSize: '21px',
            fontWeight: 600,
            marginBottom: '38px',
          }}
        >
          欢迎使用
        </div>
        <Form name="normal_login" initialValues={{ remember: true }} onFinish={handleSubmit}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名!' }]}>
            <Input
              className={styles.loginInput}
              prefix={<UserOutlined className="site-form-item-icon" />}
              placeholder="请输入用户名"
            />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码!' }]}>
            <Input
              className={styles.loginInput}
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="请输入密码"
            />
          </Form.Item>
          {/* {code !== 0 && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: msg,
              })}
            />
          )} */}
          <Form.Item>
            <Button className={styles.loginButton} type="primary" block htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Login;
